package com.uni.crawl.job;

import cn.hutool.core.bean.BeanUtil;
import com.uni.crawl.common.enums.crawl.CrawlInstanceStatusEnum;
import com.uni.crawl.model.entity.crawl.CrawlInstance;
import com.uni.crawl.model.entity.crawl.CrawlTemplate;
import com.uni.crawl.service.crawl.CrawlInstanceService;
import com.uni.crawl.service.crawl.CrawlTemplateService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

@Component
@Slf4j
@AllArgsConstructor
public class CrawlInstanceGenerateJob extends AbstractJob {

    private final CrawlTemplateService crawlTemplateService;
    private final CrawlInstanceService crawlInstanceService;

    @XxlJob("crawlInstanceGenerateJob")
    @Override
    public ReturnT<String> handle() {
        for (CrawlTemplate tmpl : crawlTemplateService.listScheduleTemplate()) {
            CrawlInstance ins = BeanUtil.toBean(tmpl, CrawlInstance.class);
            ins.setInstanceStatus(CrawlInstanceStatusEnum.INIT.getStatus());

            // 已开启，且未运行过
            // 已开启，且上次运行时间超过设定周期
            if (tmpl.getLastRunTime() == null
                    || Duration.between(tmpl.getLastRunTime(), LocalDateTime.now()).toHours() > tmpl.getSchedHour()) {
                tmpl.setLastRunTime(LocalDateTime.now());
                log.info("gen instance. tmplCode = {}, lastRunTime = {}", tmpl.getTmplCode(), tmpl.getLastRunTime());
                tmpl.setLastRunTime(LocalDateTime.now());
                crawlInstanceService.save(ins);
                crawlTemplateService.updateById(tmpl);
            }
        }
        return success();
    }
}
